package com.atguigu.lease.web.app.service.impl;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.common.utils.VerifyCodeUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.SmsService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.atguigu.lease.web.app.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.rmi.dgc.Lease;
import java.util.concurrent.TimeUnit;


@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserInfoService userInfoService;

    @Override
    public void getSMSCode(String phone) {
        // 1、检查电话是否为空
        if (phone == null) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        String key = RedisConstant.APP_CODE_PHONE_PREFIX + phone;
        // 2、检查发送验证码时间过于频繁
        if (redisTemplate.hasKey(key)) {
            Long expire = redisTemplate.getExpire(key, TimeUnit.SECONDS);
            if (RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC - expire < RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC) {
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }
        String code = VerifyCodeUtil.getVerifyCode(6);
        // 3、发送短信
        smsService.sendCode(phone, code);

        // 4、存入redis
        redisTemplate.opsForValue().set(key,code,RedisConstant.APP_LOGIN_CODE_TTL_SEC,TimeUnit.SECONDS);
    }

    @Override
    public String login(LoginVo loginVo) {
        // 1、校验空数据
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();

        if (!StringUtils.hasText(phone)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        if (!StringUtils.hasText(code)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }
        // 2、比对验证码
        String codeFromRedis = (String) redisTemplate.opsForValue().get(RedisConstant.APP_CODE_PHONE_PREFIX + phone);

        if (!StringUtils.hasText(codeFromRedis)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }

        if (!codeFromRedis.equals(code)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }
        // 3、查询用户，如果是新用户：创建新用户；如果是老用户并且被禁用则不让登陆
        UserInfo user = userInfoService.getOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getPhone, phone));

        if (user == null) {
            user = new UserInfo();
            user.setPhone(phone);
            userInfoService.save(user);
        }
        // 4、返回JWT
        return JwtUtil.createToken(user.getId(), user.getPhone());
    }

    @Override
    public UserInfoVo getUserInfoId(Long userId) {
        UserInfo user = userInfoService.getById(userId);
        UserInfoVo userInfoVo = new UserInfoVo(user.getNickname(), user.getAvatarUrl());
        return userInfoVo;
    }
}
